package com.pactera.mavenweb.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.pactera.mavenweb.dao.GroupDao;
import com.pactera.mavenweb.dao.GroupRoleDao;
import com.pactera.mavenweb.dao.UserDao;
import com.pactera.mavenweb.dao.UserRoleDao;
import com.pactera.mavenweb.entity.Group;
import com.pactera.mavenweb.entity.UserGroup;
import com.pactera.mavenweb.entity.User;
import com.pactera.mavenweb.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
	
	/**
	 * 注入dao
	 */
	@Resource(name = "userDao")
	private UserDao userDao;
	
	/**
	 * 注入dao
	 */
	@Resource(name = "groupRoleDao")
	private GroupRoleDao groupRoleDao;
	
	/**
	 * 注入dao
	 */
	@Resource(name = "userRoleDao")
	private UserRoleDao userRoleDao;
	
	/**
	 * 注入dao
	 */
	@Resource(name = "groupDao")
	private GroupDao groupDao;
	
//	@Override
	public int saveUsers(List<User> users) {
		try {
			for (User user : users) {
				userDao.saveUser(user);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return 0;
	}
	
//	@Override
	public List<User> getAllUser() {
		return userDao.queryAll();
	}
	
//	@Override
	public User getUserByName(String username) {
		return userDao.queryByName(username);
		
	}
	
//	@Override
	public void addUser(User User) {
		userDao.saveUser(User);
	}
	
//	@Override
	public void addUserSimpleRoles(User user) {
		user.setPassword(user.getName());
		
		Group group = groupDao.queryById(2);
		
		Set<UserGroup> UserGroupSet = new HashSet<UserGroup>();
		UserGroup UserGroup = new UserGroup();
		UserGroup.setGroup(group);
		UserGroup.setUser(user);
		UserGroupSet.add(UserGroup);
		
		user.setUserGroup(UserGroupSet);
		
		addUser(user);
	}
	
//	@Override
	public boolean delUser(int id) {
		
		userDao.delete(id);
		
		return true;
	}
	
//	@Override
	public void updateUser(User user) {
		User currentUser = userDao.queryByName(user.getName());
		currentUser.setName(user.getName());
		currentUser.setPhonenum(user.getPhonenum());
		userDao.update(currentUser);
	}
	
//	@Override
	public User getUserByNameWithAuth(String name) {
		User user = userDao.queryByNameWithAuth(name);
		return user;
	}
	
//	@Override
	public User getUser(int id) {
		return userDao.queryById(id);
	}
}